<?php
namespace App\Controllers\Admin;
use Mount, Area, Machine, Picture,Customer,Pub,Cache,Wechat;
use Input, Notification, Redirect, Sentry, Str;

class MountsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /admin/mounts
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /admin/mounts/create
	 *
	 * @return Response
	 */
	public function create()
	{
		//
        $METHOD = 'services';
        $ACTION = 'mounts';
        $provinces = Area::where('level',1)->get();
        $machines = Machine::all();
        return \View::make('admin.mounts.create',compact('METHOD','ACTION','machines','provinces'));
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /admin/mounts
	 *
	 * @return Response
	 */
	public function store()
	{
		//
        $name = Input::get('mount_name');
        $mobile = Input::get('mount_mobile');
        $city = Input::get('city');
        $area_id = Input::get('area_id');
        $section_id = Input::get('section_id');
        $address = Input::get('address');
        $machine = Input::get('machine');
        $created_at = Input::get('create_time');
        Mount::insert_try(null,$name,$mobile,$address,1,$area_id,$section_id,'',$city,$machine,null,3,'old',$created_at);

        return Redirect::route('admin.services.mounts');
	}

	/**
	 * Display the specified resource.
	 * GET /admin/mounts/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
        $mount = Mount::find($id);
        return \View::make('admin.mounts.show',compact('mount'));
	}

    public function pedit($id){
        $type = 1;//为修改
        return \View::make('admin.mounts.pcreate',compact('type','id'));
    }

    public function pcreate($id){
        $type = 2;//为新增
        return \View::make('admin.mounts.pcreate',compact('type','id'));
    }
    public function pstore(){

        $type = Input::get('type');
        if($type == 2){

            $mount_id = Input::get('id');
            require app_path().'/lib/qiniu/rs.php';
            require app_path().'/lib/qiniu/io.php';
            $key = $this->uploadfile($_FILES["cover"]["name"],$_FILES["cover"]["tmp_name"]);
            $picture = new Picture();
            $picture->path = "http://aebo.qiniudn.com/".$key;
            $picture->mount_id = $mount_id;
            $picture->save();


            return Redirect::route('admin.services.mounts');


        }elseif($type == 1){
            require app_path().'/lib/qiniu/rs.php';
            require app_path().'/lib/qiniu/io.php';

            $key = $this->uploadfile($_FILES["cover"]["name"],$_FILES["cover"]["tmp_name"]);

            $picture = Picture::find(Input::get('id'));
            $picture->path = "http://aebo.qiniudn.com/".$key;
            $picture->save();
            return Redirect::route('admin.services.mounts');
        }
    }

    public function delete_picture(){
        $id = Input::get('id');
        $picture = Picture::destroy($id);
        echo '<script>alert("删除成功！");</script>';

        header('Location: '.$_SERVER['HTTP_REFERER']);
//        return Redirect($_SERVER['HTTP_REFERER']);

    }



    public function get_mount_code(){
        $pub = Pub::find(1);
        if (Cache::has('token'))
        {
            //
            $value = Cache::get('token');
        }else{
            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
            Cache::put('token', $value, 240);
        }
        $id = Input::get('id');
        $id = (int)$id;
        $true = $id;
        $arr['ticket'] = Wechat::get_pic($value,$true,1,false);
        if($arr['ticket'] == 'error'){
            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
            Cache::put('token', $value, 240);
            $arr['ticket'] = Wechat::get_pic($value,$true,1,false);
        }
        echo '<img src="'.$arr['ticket'].'">';
    }



    public function section(){
        $id = Input::get('id');
        $type = Input::get('type');
        $mount = Mount::find($id);
        $customer = Customer::find($mount->customer_id);
        $customer->area = $type;
        $customer->save();
        echo 1;
    }

    public function xiaoqu(){

        $id = Input::get('id');
        $type = Input::get('type');
        $mount = Mount::find($id);


        $area_old = Area::find($mount->area_id);

        $area_old->mount_count = $area_old->mount_count-1;
        $area_old->save();

        $area_new = Area::find($type);

        $area_new->mount_count = $area_new->mount_count+1;
        $area_new->save();

        $mount->area_id = $type;
        $mount->save();



        echo 1;
    }


    public function uploadfile($name,$tmp){
        $type=array("jpg","gif","bmp","jpeg","png");//设置允许上传文件的类型

        if(!in_array(strtolower($this->fileext($name)),$type))
        {
            $text=implode(",",$type);
            echo "您只能上传以下类型文件: ",$text,"<br>";
        }
        //生成目标文件的文件名
        else{
            $filename=explode(".",$name);
            $filename[0]=$this->random(10); //设置随机数长度
            $uploadfile=implode(".",$filename);
            //$name1=$name.".Mcncc";

            $result = $this->upPicTo7niu($tmp,'com',$uploadfile,'aebo');
            return $result['key'];
        }
    }


    /**
	 * Show the form for editing the specified resource.
	 * GET /admin/mounts/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
        $METHOD = 'services';
        $ACTION = 'mounts';
        $mount = Mount::find($id);
        $sections = Area::where('father_id',$mount->city)->get();
        $xiaoqus = Area::where('father_id',$mount->section_id)->where('city_id','>',0)->get();
        $from = $_SERVER["HTTP_REFERER"];

        return \View::make('admin.mounts.edit',compact('METHOD','ACTION','mount','sections','xiaoqus','from'));
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /admin/mounts/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
        $mount = Mount::find($id);
        $mount->mount_name = Input::get('mount_name');
        $mount->mount_mobile = Input::get('mount_mobile');
        $mount->section_id = Input::get('section_id');
        $mount->area_id = Input::get('area_id');
        $mount->address = Input::get('address');
        $mount->created_at = Input::get('create_time');
        $mount->save();
        return Redirect::to(Input::get('from'));
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /admin/mounts/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}


    public function ajax(){
        $id = Input::get('id');
        $item = Input::get('item');
        switch ($item)
        {
            case 'select_province':
                $datas = Area::where('level',2)->where('father_id',$id)->get();
                break;
            case 'select_city':
                $datas = Area::where('level',3)->where('father_id',$id)->get();
                break;
            case 'select_section':
                $datas = Area::where('level',4)->where('father_id',$id)->get();
                break;
            default:
                echo "404";
        }
        return \View::make('admin.mounts.ajax',compact('datas'));
    }
    public function change(){
        $id = Input::get('id');
        $type = Input::get('type');
        $customer = Mount::find($id);
        $customer->state = $type;
        $customer->save();
        echo 1;
    }



    /**
     *上传图片至七牛云
     *$path 图片地址
     *$dirname 在七牛云上的文类名称
     *$filename 文件保存名称
     *$bucket 你的七牛云域名称
     */
    function upPicTo7niu($path,$dirname,$filename,$bucket){
        $contents = @file_get_contents($path);

        $storename = $dirname."/".$filename;
        $bu = $bucket.":".$storename;
        $accessKey = 'FWdy0abUDmanFns5ZArKEHjRl2e5hXeZVsLKSU7M';
        $secretKey = 'zuHKtuuL888TuuavvzbyWnGnytjW33zI1mrAql12';

        Qiniu_SetKeys($accessKey, $secretKey);
        $putPolicy = new \Qiniu_RS_PutPolicy($bu);
        $upToken = $putPolicy->Token(null);
        $putExtra = new \Qiniu_PutExtra();
        $putExtra->Crc32 = 1;
        list($ret, $err) = Qiniu_Put($upToken, $storename, $contents, $putExtra);
        return $ret;
    }
    //获取文件后缀名函数
    function fileext($filename)
    {
        return substr(strrchr($filename, '.'), 1);
    }

    function random($length)
    {
        $hash = 'CR-';
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $max = strlen($chars) - 1;
        mt_srand((double)microtime() * 1000000);
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
}